package handlers

import (
	"github.com/gin-gonic/gin"
	"github.com/medivhzhan/weapp/v2"
	"net/http"
	"sanrenx.com/xyxf/app/services"
	"sanrenx.com/xyxf/pkg/app"
	"sanrenx.com/xyxf/pkg/e"
	"sanrenx.com/xyxf/pkg/logging"
	"sanrenx.com/xyxf/pkg/utils"
	"sanrenx.com/xyxf/pkg/wechat"
)

// @Tags 授权
// @Summary 小程序认证 token获取
// @Accept application/json
// @Produce  json
// @Success 200 {object} app.Response
// @Router /app/v1/auth/mp [POST]
func AuthMPV2(c *gin.Context) {
	var (
		openID  string
		unionID string
		userSrv services.UserSrv
		params  struct {
			Platform string `json:"platform" binding:"required"`
			Code     string `json:"code" binding:"required"`
		}
	)

	appG := app.Gin{C: c}
	//校验绑定参数
	if err := c.ShouldBindJSON(&params); err != nil {
		app.MarkErrors(err)
		appG.Response(http.StatusBadRequest, e.InvalidParams, nil)
		return
	}

	//微信小程序
	if params.Platform == "weixin" {
		//根据 js-code 获取用户 session 信息
		var wxConf wechat.WX
		res, wxErr := weapp.Login(wxConf.AppID(), wxConf.AppSecret(), params.Code)
		if wxErr != nil {
			// 处理一般错误信息
			logging.Error(wxErr)
			appG.Response(http.StatusInternalServerError, e.ErrorAuth, nil)
			return
		}
		//复制 openid 和 unionid
		openID, unionID = res.OpenID, res.UnionID
	}

	//检查是否新用户 并获取或者创建
	exists, data, dbErr := userSrv.LoginByMP(openID, unionID, params.Platform)
	if dbErr != nil {
		logging.Error(dbErr)
		appG.Response(http.StatusInternalServerError, e.ErrorCreateUserFail, nil)
		return
	}

	//根据用户信息生成token
	token, tErr := utils.GenerateToken(data.ID, data.Phone, "user")
	if tErr != nil {
		appG.Response(http.StatusInternalServerError, e.ErrorAuthToken, nil)
		return
	}

	//返回信息
	appG.Response(http.StatusOK, e.SUCCESS, map[string]interface{}{
		"newbie": !exists,     //是否新用户
		"openid": data.Openid, //三方平台ID
		"token":  token,       //token
	})

}
